package com.ruoyi.monitormanage.controller;

import com.ruoyi.monitormanage.domain.TCreategps;
import com.ruoyi.monitormanage.domain.TTestpoint;
import com.ruoyi.monitormanage.mapper.TCreategpsMapper;
import com.ruoyi.monitormanage.mapper.TTestpointMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@EnableScheduling
public class SpringScheduledTask {
    @Autowired
    private TCreategpsMapper tCreategpsMapper;

    @Autowired
    private TTestpointMapper tTestpointMapper;

    // 每分钟执行一次（每分钟的第0秒执行）
    /*@Scheduled(cron = "0 * * * * ?")
    public void scheduledTask() {
        try {
            System.out.println("Spring定时任务执行: " + new java.util.Date());
            yourBusinessMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    // 或者使用 fixedRate（单位：毫秒）
    @Scheduled(fixedRate = 60 * 1000)
    public void scheduledTaskWithFixedRate() {
        try {
            BusinessMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void BusinessMethod() {
        //查询creategps表中的今日的数据，并且现在的时间日期大于生效的时间日期  list
        String today = LocalDate.now().toString();
        String currentYear = Integer.toString(Year.now().getValue());
        String currentDateTime = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        TCreategps tCreategps = new TCreategps();
        tCreategps.setCreatetime(today);
        tCreategps.setYear(currentYear);
        tCreategps.setEffectivetime(currentDateTime);
        List<TCreategps> creategpsList = tCreategpsMapper.selectGobyTCreategpsList(tCreategps);
        //循环处理数据，查询条件是deptid和year，将gps更新到testpoint表中，并将表中的status字段改为1（可用）。
        if (creategpsList.size()>0){
            for (TCreategps temp : creategpsList){
                TTestpoint testpoint = tTestpointMapper.getTestpoint(temp.getYear(), temp.getDeptid());
                testpoint.setGps(temp.getGps());
                testpoint.setStatus("1");
                tTestpointMapper.updateTTestpoint(testpoint);
            }
        }

    }
}
